package com.hfzy.ihk.web.linkcall.controller.flow.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.facade.entity.KeyValueField;
import com.hfzy.ihk.common.facade.enums.CustomerNeedLevel;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.date.DateUtils;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.CustomerAnswerWay;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlow;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlowStep;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingPackage;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.type.IndustryType;
import com.hfzy.ihk.facade.linkcall.entity.task.CallTask;
import com.hfzy.ihk.facade.linkcall.enums.*;
import com.hfzy.ihk.facade.linkcall.vo.flow.config.*;
import com.hfzy.ihk.web.linkcall.support.annotation.ReceiveUserPrivParam;
import com.hfzy.ihk.web.linkcall.biz.CallTaskBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.type.IndustryTypeBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.CustomerAnswerWayBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingFlowBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingFlowStepBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingPackageBiz;
import com.hfzy.ihk.web.linkcall.utils.UserUtils;
import com.hfzy.ihk.web.linkcall.utils.WebResultUtils;
import org.apache.tomcat.util.buf.StringUtils;
import org.elasticsearch.common.UUIDs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 *话术配置
 * */
@Controller
@RequestMapping("/flowConfig")
public class FlowConfigController {

    Logger logger = LoggerFactory.getLogger(FlowConfigController.class);

    @Autowired
    SpeakingPackageBiz speakingPackageBiz;

    @Autowired
    SpeakingFlowBiz speakingFlowBiz;

    @Autowired
    SpeakingFlowStepBiz speakingFlowStepBiz;

    @Autowired
    CustomerAnswerWayBiz customerAnswerWayBiz;

    @Autowired
    CallTaskBiz callTaskBiz;

    @Autowired
    IndustryTypeBiz industryTypeBiz;

    /**
     * =============================================话术包=========================================================================
     * */
    @RequestMapping("/querySpeakingPackage")
//    @ReceiveUserPrivParam
    public String querySpeakingPackage(Model model){
        model.addAttribute("types",SpeakingPackageType.values());
        return "page/flow/config/querySpeakingPackage";
    }

    @RequestMapping("/addSpeakingPackage")
    public String addSpeakingPackage(@RequestParam String id, Model model){
        String selVal = "";
        if(!"0".equals(id)){
            SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(id);
            speakingPackage.setSpeakingPackageUseage(SpeakingPackageUseage.PROPERTYHOUSE);//目前设定为房产类
            model.addAttribute("speakingPackage",speakingPackage);
            if(speakingPackage.getHadIndustryTypeId()!=null && !speakingPackage.getHadIndustryTypeId().isEmpty())
                selVal = StringUtils.join(speakingPackage.getHadIndustryTypeId(), ',');
        }
        model.addAttribute("types",SpeakingPackageType.values());
        model.addAttribute("speakingPackageUseage",SpeakingPackageUseage.PROPERTYHOUSE.getValue());//目前设定为房产类
        Map treeMap = industryTypeBiz.queryByTree("","treeNode",selVal,false,false);
        if(treeMap!=null && treeMap.containsKey("data"))
            model.addAttribute("treeMap",treeMap.get("data"));
        return "page/flow/config/addSpeakingPackage";
    }

    @ResponseBody
    @RequestMapping("/querySpeakingPackagePage")
    public WebResult querySpeakingPackagePage(@RequestParam Map<String,String> params){
        WebResult webResult = WebResultUtils.getFailCharWebResult("");
        try{
            List<Map<String,Object>> speakingPackageList = new ArrayList<>();
            Page<SpeakingPackage> speakingPackagePage = speakingPackageBiz.getSpeakingPackageByPage(params);
            Set<String> industryTypeIds = new HashSet<>();
            if(speakingPackagePage.getContent()!=null && !speakingPackagePage.getContent().isEmpty()){
                List<String> uids = speakingPackagePage.getContent().stream().map(it->it.getCreateUserId()+"").collect(Collectors.toList());
                Map<Integer,String> userMap = UserUtils.getUserNameMap(uids);
                for(SpeakingPackage speakingPackage:speakingPackagePage.getContent()){
                    Map speakingPackagMap = new HashMap();
                    if(speakingPackage.getHadIndustryTypeId()!=null && !speakingPackage.getHadIndustryTypeId().isEmpty()){
                        industryTypeIds.addAll(speakingPackage.getHadIndustryTypeId());
                        speakingPackagMap.put("selIndutryTypeIds",StringUtils.join(speakingPackage.getHadIndustryTypeId(),','));
                    }else{
                        speakingPackagMap.put("selIndutryTypeIds","");
                    }
                    speakingPackagMap.put("packageName",speakingPackage.getPackageName());
                    speakingPackagMap.put("packageType",speakingPackage.getPackageType()!=null?speakingPackage.getPackageType().getDesc():"");
                    speakingPackagMap.put("createUserName",userMap.get(speakingPackage.getCreateUserId())!=null?userMap.get(speakingPackage.getCreateUserId()):"系统管理员");
                    speakingPackagMap.put("id",speakingPackage.getId());
                    speakingPackagMap.put("createTime", DateUtils.toString(speakingPackage.getCreateTime(),DateUtils.DATE_FORMAT_DATEONLY));
                    speakingPackagMap.put("checkStatus", speakingPackage.getCheckStatus()!=null?speakingPackage.getCheckStatus().getDesc():CheckStatus.NO.getDesc());
                    speakingPackageList.add(speakingPackagMap);
                }

                //
                if(industryTypeIds!=null){
                    Map industryParam = new HashMap();
                    industryParam.put("ids",StringUtils.join(industryTypeIds,','));
                    List<IndustryType> industryTypes = industryTypeBiz.getIndustryTypesList(industryParam);
                    if(industryTypes!=null && !industryTypes.isEmpty()){
                        Map<String,String> industryMap = industryTypes.stream().collect(Collectors.toMap(IndustryType::getId, IndustryType::getName));

                        speakingPackageList.forEach(it->{
                            String selIndutryTypeIds = it.get("selIndutryTypeIds").toString();
                            if(!Utils.isNullString(selIndutryTypeIds)){
                                StringBuffer selIndutryTypeName = new StringBuffer();
                                Arrays.asList(selIndutryTypeIds.split(",")).stream().forEach(s->{
                                    if(!Utils.isNullString(industryMap.get(s))){
                                        selIndutryTypeName.append(industryMap.get(s)+",");
                                    }
                                });
                                if(selIndutryTypeName.length()>0){
                                    it.put("selIndutryTypeName",selIndutryTypeName.toString().substring(0,selIndutryTypeName.toString().length()-1));
                                }
                            }
                        });
                    }
                }
            }
            webResult = WebResultUtils.getSuccessCharWebResult("",speakingPackagePage.getTotalElements(),speakingPackageList);
        }catch (Exception e){
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
            e.printStackTrace();
        }
        return webResult;
    }

    @ResponseBody
    @RequestMapping("/viewSeakingPackage")
    public WebResult viewSeakingPackage(@RequestParam String id, Model model){
        WebResult webResult = null;
        try {
            SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(id);
            Map<String,Object> callTaskMap = new HashMap<>();
            if(speakingPackage!=null){
                Map<Integer,String> userMap = UserUtils.getUserNameMap(speakingPackage.getCreateUserId());
                callTaskMap.put("packName",speakingPackage.getPackageName());
                callTaskMap.put("createTime", DateUtils.toString(speakingPackage.getCreateTime(),DateUtils.DATE_FORMAT_DATEONLY));
                callTaskMap.put("packageType",speakingPackage.getPackageType().getDesc());//任务状态
                callTaskMap.put("createUserName",userMap.get(speakingPackage.getCreateUserId())!=null?userMap.get(speakingPackage.getCreateUserId()):"系统管理员");//创建人
                callTaskMap.put("id",speakingPackage.getId());//已call量
                model.addAttribute("speakingPackage",speakingPackage);
                webResult = WebResultUtils.getSuccessCharWebResult("",0,null);
            }else {
                webResult = WebResultUtils.getFailCharWebResult("找不到对应的话术");
            }
        }catch (Exception e){
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return  webResult;
    }

    @ResponseBody
    @RequestMapping("/saveSpeakingPackage")
    public WebResult saveSpeakingPackage(@RequestParam Map<String,String> params){
        WebResult webResult = null;
        try{
            Set<String> keySet = params.keySet();
            SpeakingPackageUseage speakingPackageUseage = SpeakingPackageUseage.PROPERTYHOUSE;
            if(params.containsKey("speakingPackageUseage") && !Utils.isNullString(params.get("speakingPackageUseage"))){
                speakingPackageUseage  = SpeakingPackageUseage.fromValue(params.get("speakingPackageUseage"));
            }
            if(keySet.contains("id") && !Utils.isNullString(params.get("id")) && !"0".equals(params.get("id"))){
                SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(params.get("id"));
                speakingPackage.setSpeakingPackageUseage(speakingPackageUseage);
                if(speakingPackage!=null){
                    Iterator entries = params.entrySet().iterator();
                    while (entries.hasNext()) {
                        Map.Entry entry = (Map.Entry) entries.next();
                        String key = entry.getKey().toString();
                        switch (key) {
                            case "packageName":
                                speakingPackage.setPackageName(params.get("packageName"));
                                break;
                          /*  case "packageType":
                                speakingPackage.setPackageType(SpeakingPackageType.fromValue(params.get("packageType")));
                                break;*/
                            case "hadIndustryTypeId":
//                                speakingPackage.setHadIndustryTypeId(Arrays.asList(params.get("hadIndustryTypeId").split(",")));
                                Set<String> relationIds = new HashSet<String>();
                                for (String id:params.get("hadIndustryTypeId").split(",")){
                                    IndustryType industryType = industryTypeBiz.selectById(id);
                                    relationIds = getRelationIds(industryType, relationIds);
                                }
                                speakingPackage.setHadIndustryTypeId(new ArrayList<>(relationIds));

                                break;
                            default:
                                break;
                        }
                    }
                    webResult = speakingPackageBiz.saveSpeakingPackage(speakingPackage);
                }
            }else{
                SpeakingPackage speakingPackage = new SpeakingPackage();
                speakingPackage.setPackageName(params.get("packageName"));
//                speakingPackage.setPackageType(SpeakingPackageType.fromValue(params.get("packageType")));
                speakingPackage.setCreateUserId(11);
                speakingPackage.setSpeakingPackageUseage(speakingPackageUseage);

                if(params.containsKey("hadIndustryTypeId")){
                    Set<String> relationIds = new HashSet<String>();
                    for (String id:params.get("hadIndustryTypeId").split(",")){
                        IndustryType industryType = industryTypeBiz.selectById(id);
                        relationIds = getRelationIds(industryType, relationIds);
                    }
                    speakingPackage.setHadIndustryTypeId(new ArrayList<>(relationIds));

                }
                webResult = speakingPackageBiz.addSpeakingPackage(speakingPackage);
            }
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }


    public Set<String> getRelationIds(IndustryType industryType,Set<String> relationIds){

        if(industryType!=null){
            relationIds.add(industryType.getId());
            if(!Utils.isNullString(industryType.getParentId()) && !"0".equals(industryType.getParentId())){
                while (industryType!=null && !Utils.isNullString(industryType.getParentId()) && !"0".equals(industryType.getParentId())){
                    if(relationIds.add(industryType.getParentId())){//判断原有的不存在 关系中则 通过id 获取 继续 去到最顶层
                        industryType = industryTypeBiz.selectById(industryType.getParentId());
                    }else{
                        industryType = null;
                    }
                }
            }
        }
        return relationIds;
    }

    @ResponseBody
    @RequestMapping("/updateSpeakingPackage")
    public WebResult updateSpeakingPackage(@RequestParam Map<String,String> params){
        WebResult webResult  = null;
        try{
            Set<String> keySet = params.keySet();
            if(keySet.contains("id")){
                SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(params.get("id"));
                if(speakingPackage!=null){
                    Iterator entries = params.entrySet().iterator();
                    while (entries.hasNext()) {
                        Map.Entry entry = (Map.Entry) entries.next();
                        String key = entry.getKey().toString();
                        switch (key) {
                            case "packageName":
                                speakingPackage.setPackageName(params.get("packageName"));
                                break;
                            case "packageType":
                                speakingPackage.setPackageType(SpeakingPackageType.fromValue(params.get("packageType")));
                                break;
                            case "hadIndustryTypeId":
                                speakingPackage.setHadIndustryTypeId(Arrays.asList(params.get("hadIndustryTypeId").split(",")));
                                break;
                            default:
                                break;
                        }
                    }
                    webResult = speakingPackageBiz.saveSpeakingPackage(speakingPackage);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }

    @ResponseBody
    @RequestMapping("/delSpeakingPackage")
    public WebResult delSpeakingPackage(@RequestParam String id){
        WebResult webResult = null;
        try {
            //先查询 是否已经绑定了 资料包
            Map param = new HashMap();
            param.put("pageSize","1");
            param.put("page","1");
            param.put("packageId",id);
            Page<CallTask> callTaskPage = callTaskBiz.queryCallTaskPage(param);
            if (StringTools.isNotempty(callTaskPage.getContent())) {
                webResult = WebResultUtils.getFailCharWebResult("此话术包已经绑定了call客任务，无法进行删除操作");
            }else{
                webResult = speakingPackageBiz.deleteSpeakingPackageById(id);
            }
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                return  webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return  webResult;
    }

    @ResponseBody
    @RequestMapping("/checkSpeakingPackage")
    public WebResult checkSpeakingPackage(@RequestParam String id,@RequestParam  String checkStatus){
        WebResult webResult =  WebResultUtils.getFailCharWebResult("");
        try {
            CheckStatus cs = CheckStatus.fromValue(checkStatus);
            Map<String,Object> updateMap = new HashMap<String,Object>();
            updateMap.put("checkStatus",CheckStatus.fromValue(checkStatus));
            webResult = speakingPackageBiz.updateSomeFields(id,updateMap);
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }
        return  webResult;
    }


    @RequestMapping("/speakingPackageConfig")
    public String speakingPackageConfig(@RequestParam  String packageId ,Model model){
        model.addAttribute("packageId",packageId);
        return "page/flow/config/speakingPackageConfig";
    }


    /**
     * =============================================流程设置=========================================================================
     * */
    @RequestMapping("/flowSetting")
    public String flowSetting(@RequestParam String packageId, @RequestParam String flowType, Model model){
        if(!"0".equals(packageId) && !Utils.isNullString(packageId) ){
            SpeakingFlowType speakingFlowType  = SpeakingFlowType.fromValue(flowType);
            List<SpeakingFlow> flows = speakingFlowBiz.getSpeakingFlowListByPackageIdType(packageId,speakingFlowType);
            List<SpeakingFlowVo> speakingFlowVos = new ArrayList<SpeakingFlowVo>();
            if(flows!=null && !flows.isEmpty()){
                for(SpeakingFlow speakingFlow:flows){
                    SpeakingFlowVo speakingFlowVo = new SpeakingFlowVo();
                    speakingFlowVo.setId(speakingFlow.getId());
                    speakingFlowVo.setFlowName(speakingFlow.getFlowName());
                    speakingFlowVo.setPackageId(speakingFlow.getPackageId());
                    String flowJsonStr = "";
                    if(speakingFlow.getFlowJson()!=null && !speakingFlow.getFlowJson().isEmpty()){
                        Map<String,String> keyVals= new HashMap<String,String>();
                        for(KeyValueField keyValueField:speakingFlow.getFlowJson()){
                            keyVals.put(keyValueField.getKey(),keyValueField.getValue());
                        }
                        flowJsonStr = JSON.toJSONString(keyVals);
                    }
                    speakingFlowVo.setFlowJsonStr(flowJsonStr);
                    speakingFlowVo.setSortNum(speakingFlow.getSortNum());
                    speakingFlowVos.add(speakingFlowVo);
                }
                model.addAttribute("flows",speakingFlowVos);
            }
        }
        model.addAttribute("packageId",packageId);
        model.addAttribute("flowType",flowType);
        return "page/speakingSkill/flowSetting";
    }


    @RequestMapping("/addSpeakingFlow")
    public String addSpeakingFlow(@RequestParam String packageId,@RequestParam String flowId,@RequestParam String flowType,Model model){
        if(!"0".equals(flowId) && !Utils.isNullString(flowId)){
            SpeakingFlow speakingFlow = speakingFlowBiz.getSpeakingFlowById(flowId);
            model.addAttribute("speakingFlow",speakingFlow);
        }
        model.addAttribute("packageId",packageId);
        model.addAttribute("flowType",flowType);
        return "page/flow/config/addSpeakingFlow";
    }

    //获取流程
//    @ResponseBody
    @RequestMapping("/getFlowBypackageId")
    public String getFlowBypackageId(@RequestParam String packageId,@RequestParam String flowType,Model model){
       /* WebResult webResult = null;
        if(!"0".equals(packageId) && !Utils.isNullString(packageId)){
            List<SpeakingFlow> flows = speakingFlowBiz.getSpeakingFlowListByPackageId(packageId);
            WebResultUtils.getSuccessCharWebResult("",flows.size(),flows);
        }else{
            WebResultUtils.getFailCharWebResult("");
        }
        return webResult;*/
        SpeakingFlowType speakingFlowType = SpeakingFlowType.fromValue(flowType);
        List<SpeakingFlow> flows = speakingFlowBiz.getSpeakingFlowListByPackageIdType(packageId,speakingFlowType);
        List<SpeakingFlowVo> speakingFlowVos = new ArrayList<SpeakingFlowVo>();
        if(flows!=null && !flows.isEmpty()){
            for(SpeakingFlow speakingFlow:flows){
                SpeakingFlowVo speakingFlowVo = new SpeakingFlowVo();
                speakingFlowVo.setId(speakingFlow.getId());
                speakingFlowVo.setFlowName(speakingFlow.getFlowName());
                speakingFlowVo.setPackageId(speakingFlow.getPackageId());
                String flowJsonStr = "";
                if(speakingFlow.getFlowJson()!=null && !speakingFlow.getFlowJson().isEmpty()){
                    Map<String,String> keyVals= new HashMap<String,String>();
                    for(KeyValueField keyValueField:speakingFlow.getFlowJson()){
                        keyVals.put(keyValueField.getKey(),keyValueField.getValue());
                    }
                    flowJsonStr = JSON.toJSONString(keyVals);
                }
                speakingFlowVo.setFlowJsonStr(flowJsonStr);
                speakingFlowVo.setSortNum(speakingFlow.getSortNum());
                speakingFlowVos.add(speakingFlowVo);
            }
            model.addAttribute("flows",speakingFlowVos);
        }
        return "page/speakingSkill/flowSetting::flowDivs";

    }


    //流程顺序设置
    @RequestMapping("/setFlowSort")
    public String setFlowSort(@RequestParam String packageId,String flowType,Model model){
        List<SpeakingFlow> flows =null;
        if(!Utils.isNullString(flowType)){
            flows = speakingFlowBiz.getSpeakingFlowListByPackageIdType(packageId,SpeakingFlowType.fromValue(flowType));
        }else{
            flows = speakingFlowBiz.getSpeakingFlowListByPackageId(packageId);
        }
        model.addAttribute("flows",flows);
        model.addAttribute("packageId",packageId);
        return "page/flow/config/setFlowSort";
    }

    @ResponseBody
    @RequestMapping("/saveFlowSorts")
    public WebResult saveFlowSorts(@RequestParam String packageId,@RequestParam  String flowSortStr){
        WebResult webResult = null;
        try{
            List<Map> mapList = JSON.parseArray(flowSortStr,Map.class);
            List<SpeakingFlow> flows = speakingFlowBiz.getSpeakingFlowListByPackageId(packageId);
            Map updateValMap = new HashMap();
            for(Map map : mapList){
                updateValMap.put(map.get("flowId"),map.get("sort").toString());
            }
            if(updateValMap!=null && !updateValMap.isEmpty()){
                Set<String> keys = updateValMap.keySet();
                for(SpeakingFlow speakingFlow:flows){
                    if(keys.contains(speakingFlow.getId())){
                        speakingFlow.setSortNum(Integer.parseInt(updateValMap.get(speakingFlow.getId()).toString()));
                    }
                }
                boolean flag = speakingFlowBiz.updateBatchById(flows);
                if(flag == true){
                    webResult = WebResultUtils.getSuccessCharWebResult("",0,null);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult("");
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }

    /**
     * =============================================流程节点=========================================================================
     * */
    @RequestMapping("/saveOrUpdateSpeakingFlowStep")
    public String saveOrUpdateSpeakingFlowStep(@RequestParam String packageId,@RequestParam String flowId,@RequestParam String stepId,@RequestParam String type,Model model){
        try{
            SpeakingFlowStepType speakingFlowStepType = SpeakingFlowStepType.fromValue(type);
            if(!"0".equals(stepId) && !Utils.isNullString(stepId)){
                SpeakingFlowStep speakingFlowStep = speakingFlowStepBiz.getSpeakingFlowStepById(stepId);
                if(speakingFlowStep!=null){
                    model.addAttribute("speakingFlowStep",speakingFlowStep);
                    if(speakingFlowStep.getAnswerTypes()!=null && !speakingFlowStep.getAnswerTypes().isEmpty()){
                        List<String> selCheckBoxKeys = new ArrayList<String>();
                        for(KeyValueField keyValueField:speakingFlowStep.getAnswerTypes()){
                            selCheckBoxKeys.add(keyValueField.getKey());
                        }
                        model.addAttribute("selCheckBoxKeys",selCheckBoxKeys);
                    }
                }
            }else{
                stepId = UUIDs.base64UUID();
            }
            model.addAttribute("flowId",flowId);
            model.addAttribute("stepId",stepId);
            model.addAttribute("packageId", packageId);
            model.addAttribute("type", type);
            model.addAttribute("boolVal", Bool.values());
            if(speakingFlowStepType == SpeakingFlowStepType.COMMON){
                model.addAttribute("customAnswerType", customerAnswerWayBiz.getCustomerAnswerWayByFlowStepId(stepId));
                model.addAttribute("defaultAnswerType", customerAnswerWayBiz.getFlowDefalutCustomerAnswerWay(flowId));
                model.addAttribute("userIntentionLevels", UserIntentionLevel.values());
                return "page/flow/config/saveOrUpdateSpeakingFlowStep";
            }else if(speakingFlowStepType == SpeakingFlowStepType.SKIP || SpeakingFlowStepType.fromValue(type) == SpeakingFlowStepType.MUTI_SESSION_SKIP){
                List<SpeakingFlow> speakingFlows = speakingFlowBiz.getSpeakingFlowListByPackageId(packageId);
                List<SpeakingFlow> flows = new ArrayList<SpeakingFlow>();
                for(SpeakingFlow speakingFlow:speakingFlows){
                    if(!flowId.equals(speakingFlow.getId())){
                        flows.add(speakingFlow);
                    }
                }
                model.addAttribute("mutiSessionSkipTypes", AfterAnswerOptionalType.values());
                List<SpeakingFlowSkipType> speakingFlowSkipTypes =  Lists.newArrayList(SpeakingFlowSkipType.values());
                if(flows==null || flows.isEmpty()){
                    speakingFlowSkipTypes.remove(speakingFlowSkipTypes.indexOf(SpeakingFlowSkipType.ASSIGN));
                }
                model.addAttribute("skipTypes", speakingFlowSkipTypes);
                /*List<SpeakingFlowStep> defalutSpeakingFlowStepList = speakingFlowStepBiz.getDefalutSpeakingFlowSteps();
                if(defalutSpeakingFlowStepList==null || defalutSpeakingFlowStepList.isEmpty()){//判断是空的时候就不加载
                    speakingFlowSkipTypes.remove(SpeakingFlowSkipType.ASSIGN_STEP);
                }*/
                model.addAttribute("flows", flows);
//                model.addAttribute("speakingFlowStepList", defalutSpeakingFlowStepList);
                return "page/flow/config/saveOrUpdateSkipSpeakingFlowStep";
            }
        }catch (Exception e){
            model.addAttribute("errorMsg",e.getMessage());
        }
        return "error";
    }


    /**
     * 通过vo 进行更新操作
     * */
    @RequestMapping("/saveOrUpdateSpeakingFlowStepById")
    public String saveOrUpdateSpeakingFlowStepById(@RequestParam String stepId,@RequestParam String type,@RequestParam String flowStepVo,Model model){
        try{
            if(!Utils.isNullString(stepId)){
                SpeakingFlowStep speakingFlowStep = speakingFlowStepBiz.getSpeakingFlowStepById(stepId);
                if(speakingFlowStep == null){
                    speakingFlowStep = new SpeakingFlowStep();
                }
                if(SpeakingFlowStepType.fromValue(type) == SpeakingFlowStepType.COMMON){
                    CommonFlowStepVo commonFlowStepVo = JSON.parseObject(flowStepVo,CommonFlowStepVo.class);
                    speakingFlowStep.setStepName(commonFlowStepVo.getName());
                    trunSpeakingFlowStepByVo(speakingFlowStep,type,commonFlowStepVo);
                    if(speakingFlowStep.getAnswerTypes()!=null && !speakingFlowStep.getAnswerTypes().isEmpty()){
                        List<String> selCheckBoxKeys = new ArrayList<String>();
                        for(KeyValueField keyValueField:speakingFlowStep.getAnswerTypes()){
                            selCheckBoxKeys.add(keyValueField.getKey());
                        }
                        model.addAttribute("selCheckBoxKeys",selCheckBoxKeys);
                    }
                    model.addAttribute("speakingFlowStep",speakingFlowStep);
                    model.addAttribute("customAnswerType", customerAnswerWayBiz.getCustomerAnswerWayByFlowStepId(speakingFlowStep.getId()));
                    model.addAttribute("defaultAnswerType", customerAnswerWayBiz.getFlowDefalutCustomerAnswerWay(speakingFlowStep.getFlowId()));
                    model.addAttribute("userIntentionLevels", UserIntentionLevel.values());
                    model.addAttribute("boolVal", Bool.values());
                    model.addAttribute("flowId",speakingFlowStep.getFlowId());
                    model.addAttribute("type", speakingFlowStep.getType().getValue());
                    model.addAttribute("stepId", stepId);
                    model.addAttribute("packageId", speakingFlowStep.getPackageId());
                    return "page/flow/config/saveOrUpdateSpeakingFlowStep";
                }else if(SpeakingFlowStepType.fromValue(type) == SpeakingFlowStepType.SKIP || SpeakingFlowStepType.fromValue(type) == SpeakingFlowStepType.MUTI_SESSION_SKIP ){
                    SkipFlowStepVo skipFlowStepVo = JSON.parseObject(flowStepVo,SkipFlowStepVo.class);
                    trunSpeakingFlowStepByVo(speakingFlowStep,type,skipFlowStepVo);
                    List<SpeakingFlow> speakingFlows = speakingFlowBiz.getSpeakingFlowListByPackageId(speakingFlowStep.getPackageId());
                    List<SpeakingFlow> flows = new ArrayList<SpeakingFlow>();
                    for(SpeakingFlow speakingFlow:speakingFlows){
                        if(!speakingFlowStep.getFlowId().equals(speakingFlow.getId())){
                            flows.add(speakingFlow);
                        }
                    }

                    model.addAttribute("mutiSessionSkipTypes", AfterAnswerOptionalType.values());
                    List<SpeakingFlowSkipType> ssts =  Arrays.asList(SpeakingFlowSkipType.values());
//                   ArrayList报错：UnsupportedOperationException的
                    List speakingFlowSkipTypes=new ArrayList(ssts);
                    if(flows.size()==0){
                        speakingFlowSkipTypes.remove(SpeakingFlowSkipType.ASSIGN);
                    }
                    model.addAttribute("skipTypes", speakingFlowSkipTypes);
                  /*   List<SpeakingFlowStep> defalutSpeakingFlowStepList = speakingFlowStepBiz.getDefalutSpeakingFlowSteps();
                   if(defalutSpeakingFlowStepList==null || defalutSpeakingFlowStepList.isEmpty()){//判断是空的时候就不加载
                        speakingFlowSkipTypes.remove(SpeakingFlowSkipType.ASSIGN_STEP);
                    }
                    model.addAttribute("speakingFlowStepList", defalutSpeakingFlowStepList);*/
                    model.addAttribute("speakingFlowStep",speakingFlowStep);
                    model.addAttribute("flows", flows);
                    model.addAttribute("flowId",speakingFlowStep.getFlowId());
                    model.addAttribute("type", speakingFlowStep.getType().getValue());
                    model.addAttribute("stepId", stepId);
                    model.addAttribute("packageId", speakingFlowStep.getPackageId());
                    return "page/flow/config/saveOrUpdateSkipSpeakingFlowStep";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("errorMsg",e.getMessage());
        }
        return "error";
    }


    @ResponseBody
    @RequestMapping("/trunFlowStepJson")
    public JSON trunFlowStepJson(@RequestParam Map<String,String> params){
        System.out.println(params);
        JSONObject jsonObject = null;
        try{
            SpeakingFlowStep speakingFlowStep = null;
            if(!"0".equals(params.get("id")) && !Utils.isNullString(params.get("id"))){
                speakingFlowStep = speakingFlowStepBiz.getSpeakingFlowStepById(params.get("id"));
                if(speakingFlowStep == null){
                    speakingFlowStep = new SpeakingFlowStep();
                    speakingFlowStep.setId(params.get("id"));
                }
                Iterator entries = params.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    String key = entry.getKey().toString();
                    if (entry.getValue()!=null) {
                        switch (key) {
                            case "stepName":
                                speakingFlowStep.setStepName(params.get("stepName"));
                                break;
                            case "content":
                                speakingFlowStep.setContent(params.get("content"));
                                break;
                            case "flowId":
                                if (!Utils.isNullString(params.get("flowId"))){
                                    speakingFlowStep.setFlowId(params.get("flowId"));
                                }
                                break;
                            case "answerType":
                                String answerTypes = params.get("answerType");
                                if(!StringUtil.isEmpty(answerTypes)){
                                    List<String> answerTypeList = Arrays.asList(answerTypes.split(","));
                                    List<KeyValueField> list = new ArrayList<>();
                                    for(int i=0;i<answerTypeList.size();i++){
                                        CustomerAnswerWay customerAnswerWay = customerAnswerWayBiz.getCustomerAnswerWayById(answerTypeList.get(i));
                                        list.add(new KeyValueField(customerAnswerWay.getId(), customerAnswerWay.getName()));
                                    /*if(answerTypeList.get(i).contains("custom_")){
                                        CustomerAnswerWay customCustomerAnswerType = customerAnswerWayBiz.getCustomerAnswerWayById(answerTypeList.get(i).replaceFirst("custom_",""));
                                        list.add(new KeyValueField(customCustomerAnswerType.getTypeKey(), customCustomerAnswerType.getName()));
                                    }else{
                                        CustomerAnswerType customerAnswerType = CustomerAnswerType.fromValue(answerTypeList.get(i));
                                        list.add(new KeyValueField(customerAnswerType.getValue(), customerAnswerType.getDesc()));
                                    }*/
                                    }
                                    speakingFlowStep.setAnswerTypes(list);
                                }
                                break;
                            case "userIntentionLevel":
                                if(!StringUtil.isEmpty(params.get("userIntentionLevel"))){
                                    speakingFlowStep.setCustomerNeedLevel(CustomerNeedLevel.fromValue(params.get("userIntentionLevel")));
                                }
                                break;
                            case "packageId":
                                if(!Utils.isNullString(params.get("packageId")))
                                    speakingFlowStep.setPackageId(params.get("packageId"));
                                else{
                                    SpeakingFlow speakingFlow = speakingFlowBiz.getSpeakingFlowById(params.get("flowId"));
                                    speakingFlowStep.setFlowId(speakingFlow.getId());
                                }
                                break;
                            case "skipType":
                                if(!StringUtil.isEmpty(params.get("skipType"))){
                                    speakingFlowStep.setSkipType(SpeakingFlowSkipType.fromValue(params.get("skipType")));
                                }
//                                skipFlowStepVo.setNextflowName(SpeakingFlowSkipType.fromValue(params.get("skipType")).getDesc());
                                break;
                            case "skipFlowId":
                                speakingFlowStep.setSkipFlowId(params.get("skipFlowId"));
                                break;
                            case "skipFlowStepId":
                                speakingFlowStep.setSkipFlowStepId(params.get("skipFlowStepId"));
                                break;
                            case "actionCodeBreak":
                                if("true".equals(params.get("actionCodeBreak")) || "false".equals(params.get("actionCodeBreak"))){
                                    speakingFlowStep.setActionCodeBreak(Boolean.parseBoolean(params.get("actionCodeBreak")));
                                }
                                break;
                            case "mutiSessionSkipType":
                                if(!StringUtil.isEmpty(params.get("mutiSessionSkipType")))
                                    speakingFlowStep.setMutiSessionSkipType(AfterAnswerOptionalType.fromValue(params.get("mutiSessionSkipType")));
                                break;
                            default:
                                break;
                        }
                    }
                }
                Object obj = trunVoBySpeakingFlowStep(speakingFlowStep,params.get("type"));
                    if(obj!=null){
                    jsonObject = (JSONObject) JSON.toJSON(obj);
                }
            }
        }catch (Exception e){
           e.printStackTrace();
        }
        return  jsonObject;
    }


    /**
     * 保存流程
     * */
    @ResponseBody
    @RequestMapping("/saveSpeakingFlow")
    public WebResult saveSpeakingFlow(@RequestParam Map<String,String> params){
        WebResult webResult = null;
        try{
            Set<String> keySet = params.keySet();
            if(keySet.contains("id") && !Utils.isNullString(params.get("id")) && !"0".equals(params.get("id"))){
                SpeakingFlow speakingFlow = speakingFlowBiz.getSpeakingFlowById(params.get("id"));
                speakingFlow.setFlowType(SpeakingFlowType.fromValue(params.get("flowType")));
                if(speakingFlow!=null){
                    Iterator entries = params.entrySet().iterator();
                    while (entries.hasNext()) {
                        Map.Entry entry = (Map.Entry) entries.next();
                        String key = entry.getKey().toString();
                        switch (key) {
                            case "flowName":
                                speakingFlow.setFlowName(params.get("flowName"));
                                break;
                            case "sortNum":
                                speakingFlow.setSortNum(Integer.parseInt(params.get("sortNum")));
                                break;
                            default:
                                break;
                        }
                    }
                    webResult = speakingFlowBiz.saveSpeakingFlow(speakingFlow);
                    if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                        webResult.setMsg(speakingFlow.getId());
                    }
                }
            }else{
                SpeakingFlow speakingFlow = new SpeakingFlow();
                speakingFlow.setFlowName(params.get("flowName"));
                speakingFlow.setPackageId(params.get("packageId"));
                if(!Utils.isNullString(params.get("flowType")) && SpeakingFlowType.MAIN.getValue().equals(params.get("flowType"))){
                    if(!Utils.isNullString(params.get("sortNum")) && Utils.isNumber(params.get("sortNum"))){
                        speakingFlow.setSortNum(Integer.parseInt(params.get("sortNum")));
                    }else{
                        return WebResultUtils.getFailCharWebResult("该流程节点的顺序未填写或者填写有误！！！");
                    }
                }
                speakingFlow.setCreateUserId(11);
                speakingFlow.setFlowType(SpeakingFlowType.fromValue(params.get("flowType")));
                webResult = speakingFlowBiz.addSpeakingFlow(speakingFlow);
                if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                    webResult.setMsg(speakingFlow.getId());
                    SpeakingFlowVo speakingFlowVo = new SpeakingFlowVo();
                    speakingFlowVo.setSortNum(speakingFlow.getSortNum());
                    speakingFlowVo.setFlowJsonStr(speakingFlow.getFlowJsonStr());
                    speakingFlowVo.setPackageId(speakingFlow.getPackageId());
                    speakingFlowVo.setFlowName(speakingFlow.getFlowName());
                    speakingFlowVo.setId(speakingFlow.getId());
                    webResult.setParameter(JSON.toJSONString(speakingFlowVo));
                }
            }
        }catch (Exception e){
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }


    /**
     * 查询公用流程页面
     * */
    @RequestMapping("/queryDefaultSpeakingFlowStep")
    public String queryDefaultSpeakingFlowStep(Model model){
        return "page/flow/config/queryDefaultSpeakingFlowStep";
    }

    /**
     *
     * 获取公用的流程节点
     * */
    @ResponseBody
    @RequestMapping("/queryDefaultSpeakingFlowStepPage")
    public WebResult queryDefaultSpeakingFlowStepPage(@RequestParam Map<String,String> params){
        WebResult webResult = null;
        try{
            params.put("packageId","null");
            params.put("flowId","null");
            Page<SpeakingFlowStep> speakingFlowSteps = speakingFlowStepBiz.getSpeakingFlowStepByPage(params);
            List<Map> list = new ArrayList<>();
            if(speakingFlowSteps.getContent()!=null && !speakingFlowSteps.getContent().isEmpty()){
                List<String> uids = speakingFlowSteps.getContent().stream().map(it->it.getCreateUserId()+"").collect(Collectors.toList());
                Map<Integer,String> userMap = UserUtils.getUserNameMap(uids);
                for(SpeakingFlowStep speakingFlowStep:speakingFlowSteps.getContent()){
                    Map<String,Object> map = new HashMap<>();
                    map.put("name",speakingFlowStep.getStepName());
                    map.put("id",speakingFlowStep.getId());
                    map.put("createUserName",userMap.get(speakingFlowStep.getCreateUserId())!=null?userMap.get(speakingFlowStep.getCreateUserId()):"系统管理员");
                    map.put("modTime",Utils.date2DateTimeString(speakingFlowStep.getModTime()));
                    list.add(map);
                }
            }
            webResult = WebResultUtils.getSuccessCharWebResult("",speakingFlowSteps.getTotalElements(),list);
        }catch (Exception e){
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }



    /**
     * 删除流程节点
     * */
    @ResponseBody
    @RequestMapping("/delSpeakingFlowStep")
    public WebResult delSpeakingFlowStep(@RequestParam String id){
        WebResult webResult = null;
        try {
            webResult = speakingFlowStepBiz.deleteSpeakingFlowStepById(id);
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                  webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return  webResult;
    }


    /**
     * 保存流程节点
     * */
    @ResponseBody
    @RequestMapping("/saveSpeakFlowStep")
    public WebResult saveSpeakFlowStep(@RequestParam Map<String,String> params){
        WebResult webResult = null;
        try{
            Set<String> keySet = params.keySet();
            List<SpeakingFlowStep> speakingFlowStepList = new ArrayList<SpeakingFlowStep>();
            SpeakingFlowStep speakingFlowStep = null;
            if(keySet.contains("id") && !Utils.isNullString(params.get("id")) && !"0".equals(params.get("id"))) {
                speakingFlowStep = speakingFlowStepBiz.getSpeakingFlowStepById(params.get("id"));
            }
            if(speakingFlowStep==null){
                speakingFlowStep = new SpeakingFlowStep();
            }
            if(speakingFlowStep!=null){
                Iterator entries = params.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    String key = entry.getKey().toString();
                    if (entry.getValue()!=null) {
                        switch (key) {
                            case "stepName":
                                speakingFlowStep.setStepName(params.get("stepName"));
                                break;
                            case "content":
                                speakingFlowStep.setContent(params.get("content"));
                                break;
                            case "flowId":
                                speakingFlowStep.setFlowId(params.get("flowId"));
                                break;
                            case "packageId":
                                speakingFlowStep.setPackageId(params.get("packageId"));
                                break;
                            case "skipType":
                                if(!StringUtil.isEmpty(params.get("skipType"))){
                                    speakingFlowStep.setSkipType(SpeakingFlowSkipType.fromValue(params.get("skipType")));
                                }
                                break;
                            case "skipFlowId":
                                speakingFlowStep.setSkipFlowId(params.get("skipFlowId"));
                                break;
                            case "skipFlowStepId":
                                speakingFlowStep.setSkipFlowStepId(params.get("skipFlowStepId"));
                                break;
                            case "mutiSessionSkipType":
                                if(!StringUtil.isEmpty(params.get("mutiSessionSkipType")))
                                    speakingFlowStep.setMutiSessionSkipType(AfterAnswerOptionalType.fromValue(params.get("mutiSessionSkipType")));
                                break;
                            case "type":
                                if(!StringUtil.isEmpty(params.get("type")))
                                    speakingFlowStep.setType(SpeakingFlowStepType.fromValue(params.get("type")));
                            default:
                                break;
                        }
                    }
                }
                if(!Utils.isNullString(speakingFlowStep.getId())){
                    webResult = speakingFlowStepBiz.saveSpeakingFlowStep(speakingFlowStep);
                }else{
                    speakingFlowStep.setId(params.get("id"));
                    webResult = speakingFlowStepBiz.addSpeakingFlowStep(speakingFlowStep);
                }
                speakingFlowStepList.add(speakingFlowStep);
                webResult.setRecords(speakingFlowStepList);
            }
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }

    /**
     * =============================================自定义分支[用户回答]=========================================================================
     * */
    /**
     * 查询默认分支
     * */
//    @ReceiveUserPrivParam
    @RequestMapping("/queryDefaultCustomerAnswerWay")
    public String queryDefaultCustomerAnswerWay(Model model){
        return "page/flow/config/queryDefaultCustomerAnswerWay";
    }

    @ResponseBody
    @RequestMapping("/queryDefaultCustomerAnswerWayPage")
    public WebResult queryDefaultCustomerAnswerWayPage(@RequestParam Map<String,String> params){
        WebResult webResult = null;
        try{
            Page<CustomerAnswerWay> customerAnswerWays = customerAnswerWayBiz.getCustomerAnswerWayByPage(params);
            List<Map> list = new ArrayList<Map>();
            if(customerAnswerWays.getContent()!=null && !customerAnswerWays.getContent().isEmpty()){
                List<String> uids = customerAnswerWays.getContent().stream().map(it->it.getCreateUserId()+"").collect(Collectors.toList());
                Map<Integer,String> userMap = UserUtils.getUserNameMap(uids);
                for(CustomerAnswerWay customerAnswerWay:customerAnswerWays.getContent()){
                    Map<String,Object> map = new HashMap<>();
                    map.put("name",customerAnswerWay.getName());
                    map.put("id",customerAnswerWay.getId());
                    map.put("createUserName",userMap.get(customerAnswerWay.getCreateUserId())!=null?userMap.get(customerAnswerWay.getCreateUserId()):"系统管理员");
                    map.put("modTime",Utils.date2DateTimeString(customerAnswerWay.getModTime()));
                    list.add(map);
                }
            }
            webResult = WebResultUtils.getSuccessCharWebResult("",customerAnswerWays.getTotalElements(),list);
        }catch (Exception e){
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }

    /**
     * 添加用户分支界面
     * */
    @RequestMapping("/saveOrUpdateCustomerAnswerWay")
    public  String saveOrUpdateCustomerAnswerWay(@RequestParam String flowId,@RequestParam String stepId,@RequestParam String id,Model model){
        if(!"0".equals(id) && !Utils.isNullString(id)){
            CustomerAnswerWay customerAnswerWay  = customerAnswerWayBiz.getCustomerAnswerWayById(id);
            CustomerAnswerWayVo customerAnswerWayVo = new CustomerAnswerWayVo();
            customerAnswerWayVo.setId(customerAnswerWay.getId());
            customerAnswerWayVo.setContentStr(customerAnswerWay.getContentStr());
            customerAnswerWayVo.setKeyworlds(customerAnswerWay.getKeyworldsStr());
            customerAnswerWayVo.setCreateTime(customerAnswerWay.getCreateTime());
            customerAnswerWayVo.setCreateUserId(customerAnswerWay.getCreateUserId());
            customerAnswerWayVo.setFlowId(customerAnswerWay.getFlowId());
            customerAnswerWayVo.setFlowStepId(customerAnswerWay.getFlowStepId());
            customerAnswerWayVo.setName(customerAnswerWay.getName());
            customerAnswerWayVo.setTypeKey(customerAnswerWay.getTypeKey());
            customerAnswerWayVo.setModTime(customerAnswerWay.getModTime());
            model.addAttribute("customCustomerAnswerType",customerAnswerWayVo);
            model.addAttribute("stepId",customerAnswerWayVo.getFlowStepId());
            model.addAttribute("flowId",customerAnswerWayVo.getFlowId());
        }else{
            model.addAttribute("stepId",stepId);
            model.addAttribute("flowId",flowId);
        }
        return "page/flow/config/saveOrUpdateCustomerAnswerWay";
    }

    /**
     * 保存自定义的用户回答方式
     * */
    @ResponseBody
    @RequestMapping("/saveCustomerAnswerWay")
    public WebResult saveCustomerAnswerWay(@RequestParam Map<String,String> params){
        WebResult webResult = null;
        try{
            Set<String> keySet = params.keySet();
            List<CustomerAnswerWay> customerAnswerWays = new ArrayList<CustomerAnswerWay>();
            CustomerAnswerWay customerAnswerWay = null;
            if(keySet.contains("id") && !Utils.isNullString(params.get("id")) && !"0".equals(params.get("id"))) {
                customerAnswerWay = customerAnswerWayBiz.getCustomerAnswerWayById(params.get("id"));
            }else{
                customerAnswerWay = new CustomerAnswerWay();
                customerAnswerWay.setCreateUserId(11);
            }
            if(customerAnswerWay!=null){
                Iterator entries = params.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    String key = entry.getKey().toString();
                    switch (key) {
                        case "name":
                            customerAnswerWay.setName(params.get("name"));
                            break;
                        case "flowId":
                            customerAnswerWay.setFlowId(params.get("flowId"));
                            break;
                        case "stepId":
                            customerAnswerWay.setFlowStepId(params.get("stepId"));
                            break;
                        case "content":
                            customerAnswerWay.setContent(Arrays.asList(params.get("content").split(",")));
                            break;
                        case "keyworlds":
                            customerAnswerWay.setKeyworlds(Arrays.asList(params.get("keyworlds").split(",")));
                            break;
                        default:
                            break;
                    }
                }
                if(!Utils.isNullString(customerAnswerWay.getId())){
                    webResult = customerAnswerWayBiz.saveCustomerAnswerWay(customerAnswerWay);
                }else{
                    webResult = customerAnswerWayBiz.addCustomerAnswerWay(customerAnswerWay);
                }
                customerAnswerWays.add(customerAnswerWay);
                webResult.setRecords(customerAnswerWays);
            }
        }catch (Exception e){
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }

    /**
     * 删除自定义的用户回答方式
     * */
    @ResponseBody
    @RequestMapping("/delCustomerAnswerWay")
    public WebResult delCustomerAnswerWay(@RequestParam String id){
        WebResult webResult = null;
        try {
//            speakingFlowStepBiz.getSpeakingFlowStepList()
            webResult = customerAnswerWayBiz.deleteCustomerAnswerWayById(id);
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                  webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return  webResult;
    }


    /**
     * 加载自定义的用户回答方式 -- 跟进flowId
     * */
    @ResponseBody
    @RequestMapping("/getCustomerAnswerWayByFlowStepId")
    public WebResult getCustomerAnswerWayByFlowStepId(@RequestParam String flowStepId){
        WebResult webResult = null;
        try {
            List<CustomerAnswerWay> customerAnswerWays = customerAnswerWayBiz.getCustomerAnswerWayByFlowStepId(flowStepId);
            webResult = WebResultUtils.getSuccessCharWebResult("",0,customerAnswerWays);
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                return  webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return  webResult;
    }




    @ResponseBody
    @RequestMapping("/saveFlow")
    public WebResult saveFlow(@RequestParam Map<String,String> params){
        WebResult webResult = null;
        try{
            List<SkipFlowStepVo> skipFlowStepVos = JSON.parseArray(params.get("typeSkip"),SkipFlowStepVo.class);
            List<CommonFlowStepVo> commonFlowStepVos = JSON.parseArray(params.get("typeCommon"),CommonFlowStepVo.class);
            List<StepRelationVo> stepRelationVos = JSON.parseArray(params.get("connectRelationStr"),StepRelationVo.class);

            List<SpeakingFlowStep> speakingFlowSteps = new ArrayList<SpeakingFlowStep>();
            List<String> targetIds = new ArrayList<String>();
            for (CommonFlowStepVo commonFlowStepVo:commonFlowStepVos){
                SpeakingFlowStep speakingFlowStep = new SpeakingFlowStep();
                speakingFlowStep = trunSpeakingFlowStepByVo(speakingFlowStep,SpeakingFlowStepType.COMMON.getValue(),commonFlowStepVo);
                List<KeyValueField> answerTypeRelation = new ArrayList<KeyValueField>();
                for (StepRelationVo stepRelationVo:stepRelationVos){
                    if(stepRelationVo.getSourceId().contains(commonFlowStepVo.getId())){
                        String answerType = stepRelationVo.getSourceId().replaceFirst(commonFlowStepVo.getId()+"_","");
                        String targetId = stepRelationVo.getTargetId();
                        targetIds.add(targetId);
                        answerTypeRelation.add(new KeyValueField(answerType, targetId));
                    }
                }
                if(answerTypeRelation!=null && !answerTypeRelation.isEmpty()){
                    speakingFlowStep.setAnswerTypeRelation(answerTypeRelation);
                }
                speakingFlowSteps.add(speakingFlowStep);
            }
            if(speakingFlowSteps!=null && !speakingFlowSteps.isEmpty()){//获取该流程下的 第一个流程节点
              for(SpeakingFlowStep speakingFlowStep:speakingFlowSteps){
                  System.out.println(targetIds.toString());
                  if(!targetIds.contains(speakingFlowStep.getId())){
                      speakingFlowStep.setFirstStepByFlow(true);
                  }
              }
            }

            for(SkipFlowStepVo skipFlowStepVo : skipFlowStepVos){
                SpeakingFlowStep speakingFlowStep = new SpeakingFlowStep();
                speakingFlowStep = trunSpeakingFlowStepByVo(speakingFlowStep,skipFlowStepVo.getType(),skipFlowStepVo);
                speakingFlowSteps.add(speakingFlowStep);
            }


            if(!speakingFlowSteps.isEmpty()){
                String flowId = Utils.getFirst(speakingFlowSteps).getFlowId();
                SpeakingFlow flow = speakingFlowBiz.getSpeakingFlowById(flowId);
                List<KeyValueField> flowJsons = new ArrayList<KeyValueField>();
                Iterator iterator =  params.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry entry = (Map.Entry) iterator.next();
                    flowJsons.add(new KeyValueField(entry.getKey().toString(),entry.getValue().toString()));
                }
                flow.setFlowJson(flowJsons);
                webResult = speakingFlowBiz.saveFlows(flow,speakingFlowSteps);
                List<SpeakingFlow> speakingFlows = new ArrayList<SpeakingFlow>();
                speakingFlows.add(flow);
                List<SpeakingFlowVo> speakingFlowVos = new ArrayList<SpeakingFlowVo>();
                for(SpeakingFlow speakingFlow:speakingFlows){
                    SpeakingFlowVo speakingFlowVo = new SpeakingFlowVo();
                    speakingFlowVo.setId(speakingFlow.getId());
                    speakingFlowVo.setFlowName(speakingFlow.getFlowName());
                    speakingFlowVo.setPackageId(speakingFlow.getPackageId());
                    String flowJsonStr = "";
                    if(speakingFlow.getFlowJson()!=null && !speakingFlow.getFlowJson().isEmpty()){
                        Map<String,String> keyVals= new HashMap<String,String>();
                        for(KeyValueField keyValueField:speakingFlow.getFlowJson()){
                            keyVals.put(keyValueField.getKey(),keyValueField.getValue());
                        }
                        flowJsonStr = JSON.toJSONString(keyVals);
                    }
                    speakingFlowVo.setFlowJsonStr(flowJsonStr);
                    speakingFlowVo.setSortNum(speakingFlow.getSortNum());
                    speakingFlowVos.add(speakingFlowVo);
                }
                webResult.setRecords(speakingFlowVos);
            }else{
                webResult = WebResultUtils.getFailCharWebResult("参数异常");
            }
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult("");
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }

    public  SpeakingFlowStep  trunSpeakingFlowStepByVo(SpeakingFlowStep speakingFlowStep ,String type,Object object){
        if(SpeakingFlowStepType.fromValue(type) == SpeakingFlowStepType.COMMON){
            CommonFlowStepVo commonFlowStepVo = (CommonFlowStepVo)object;
            speakingFlowStep.setContent(commonFlowStepVo.getContent());
            speakingFlowStep.setStepName(commonFlowStepVo.getName());
            speakingFlowStep.setId(commonFlowStepVo.getId());
            speakingFlowStep.setFlowId(commonFlowStepVo.getFlowId());
            speakingFlowStep.setPackageId(commonFlowStepVo.getPackageId());
            speakingFlowStep.setX(commonFlowStepVo.getX());
            speakingFlowStep.setY(commonFlowStepVo.getY());
            speakingFlowStep.setAnswerTypes(commonFlowStepVo.getAnswerTypes());
            speakingFlowStep.setType(SpeakingFlowStepType.fromValue(commonFlowStepVo.getType()));
            if(!Utils.isNullString(commonFlowStepVo.getCustomerNeedLevel())){
                speakingFlowStep.setCustomerNeedLevel(CustomerNeedLevel.fromValue(commonFlowStepVo.getCustomerNeedLevel()));
            }
            speakingFlowStep.setPackageId(commonFlowStepVo.getPackageId());
            speakingFlowStep.setActionCodeBreak(commonFlowStepVo.isActionCodeBreak());
        }else{
            SkipFlowStepVo skipFlowStepVo = (SkipFlowStepVo)object;
            speakingFlowStep.setContent(skipFlowStepVo.getContent());
            speakingFlowStep.setId(skipFlowStepVo.getId());
            speakingFlowStep.setFlowId(skipFlowStepVo.getFlowId());
            speakingFlowStep.setPackageId(skipFlowStepVo.getPackageId());
            speakingFlowStep.setStepName(skipFlowStepVo.getName());
            speakingFlowStep.setX(skipFlowStepVo.getX());
            speakingFlowStep.setY(skipFlowStepVo.getY());
            speakingFlowStep.setSkipFlowId(skipFlowStepVo.getSkipFlowId());
            speakingFlowStep.setSkipFlowStepId(skipFlowStepVo.getSkipFlowStepId());
            speakingFlowStep.setFlowId(skipFlowStepVo.getFlowId());
            speakingFlowStep.setType(SpeakingFlowStepType.fromValue(type));
            speakingFlowStep.setPackageId(skipFlowStepVo.getPackageId());
            speakingFlowStep.setActionCodeBreak(skipFlowStepVo.isActionCodeBreak());
            if(!Utils.isNullString(skipFlowStepVo.getSkipType()))
                speakingFlowStep.setSkipType(SpeakingFlowSkipType.fromValue(skipFlowStepVo.getSkipType()));
            if(!Utils.isNullString(skipFlowStepVo.getMutiSessionSkipType()))
                speakingFlowStep.setMutiSessionSkipType(AfterAnswerOptionalType.fromValue(skipFlowStepVo.getMutiSessionSkipType()));
        }
        return speakingFlowStep;
    }


    public  Object  trunVoBySpeakingFlowStep(SpeakingFlowStep speakingFlowStep ,String type){
        Object result = null;
        if(speakingFlowStep== null){
            return null;
        }
        if(SpeakingFlowStepType.fromValue(type) == SpeakingFlowStepType.COMMON){
            CommonFlowStepVo commonFlowStepVo = new CommonFlowStepVo();
            commonFlowStepVo.setType(SpeakingFlowStepType.COMMON.getValue());
            commonFlowStepVo.setId(speakingFlowStep.getId());
            commonFlowStepVo.setFlowId(speakingFlowStep.getFlowId());
            commonFlowStepVo.setPackageId(speakingFlowStep.getPackageId());
            commonFlowStepVo.setName(speakingFlowStep.getStepName());
            commonFlowStepVo.setContent(speakingFlowStep.getContent());
            commonFlowStepVo.setAnswerTypeRelation(speakingFlowStep.getAnswerTypeRelation());
            if(speakingFlowStep.getAnswerTypes()!=null && !speakingFlowStep.getAnswerTypes().isEmpty()){
                commonFlowStepVo.setAnswerTypes(speakingFlowStep.getAnswerTypes());
            }
            if(speakingFlowStep.getCustomerNeedLevel()!=null){
                commonFlowStepVo.setCustomerNeedLevel(speakingFlowStep.getCustomerNeedLevel().getValue());
            }
            commonFlowStepVo.setAnswerTypes(speakingFlowStep.getAnswerTypes());
            commonFlowStepVo.setActionCodeBreak(speakingFlowStep.isActionCodeBreak());
            result = commonFlowStepVo;
        }else if(SpeakingFlowStepType.fromValue(type) == SpeakingFlowStepType.SKIP || SpeakingFlowStepType.fromValue(type) == SpeakingFlowStepType.MUTI_SESSION_SKIP){
            SkipFlowStepVo skipFlowStepVo = new SkipFlowStepVo();
            skipFlowStepVo.setType(type);
            skipFlowStepVo.setId(speakingFlowStep.getId());
            skipFlowStepVo.setFlowId(speakingFlowStep.getFlowId());
            skipFlowStepVo.setPackageId(speakingFlowStep.getPackageId());
            skipFlowStepVo.setName(speakingFlowStep.getStepName());
            skipFlowStepVo.setContent(speakingFlowStep.getContent());
            skipFlowStepVo.setActionCodeBreak(speakingFlowStep.isActionCodeBreak());
            if(speakingFlowStep.getSkipType()!=null){
                skipFlowStepVo.setSkipType(speakingFlowStep.getSkipType().getValue());
                skipFlowStepVo.setNextflowName(speakingFlowStep.getSkipType().getDesc());
            }
            if(speakingFlowStep.getMutiSessionSkipType()!=null){
                skipFlowStepVo.setMutiSessionSkipType(speakingFlowStep.getMutiSessionSkipType().getValue());
                skipFlowStepVo.setNextflowName(speakingFlowStep.getMutiSessionSkipType().getDesc());
            }
            if(!Utils.isNullString(speakingFlowStep.getSkipFlowId()) && (SpeakingFlowSkipType.ASSIGN == speakingFlowStep.getSkipType() || AfterAnswerOptionalType.ASSIGN == speakingFlowStep.getMutiSessionSkipType())) {
                skipFlowStepVo.setSkipFlowId(speakingFlowStep.getSkipFlowId());
                SpeakingFlow nextFlow = speakingFlowBiz.getSpeakingFlowById(speakingFlowStep.getSkipFlowId());
                if(nextFlow!=null){
                    skipFlowStepVo.setNextflowName(nextFlow.getFlowName());
                }
            }
            /*if(!Utils.isNullString(speakingFlowStep.getSkipFlowStepId()) &&  SpeakingFlowSkipType.ASSIGN_STEP == speakingFlowStep.getSkipType()){
                skipFlowStepVo.setSkipFlowStepId(speakingFlowStep.getSkipFlowStepId());
                SpeakingFlowStep sfs = speakingFlowStepBiz.getSpeakingFlowStepById(speakingFlowStep.getSkipFlowStepId());
                if(sfs!=null){
                    skipFlowStepVo.setNextflowStepName(sfs.getStepName());
                }
            }*/
            result = skipFlowStepVo;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/delSpeakingFlow")
    public WebResult delSpeakingFlow(@RequestParam String flowId){
        WebResult webResult = null;
        try {
            webResult = speakingFlowBiz.deleteSpeakingFlowById(flowId);
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult("");
        }finally {
            if(webResult==null)
                webResult = WebResultUtils.getFailCharWebResult("");
       }
       return webResult;
    }


    /**
     *删除话术包 --- 同时要删除流程节点以及流程下默认分支、流程下的步骤及其分支
     * */
    @ResponseBody
    @RequestMapping("/delSpeakingPacking")
    public WebResult delSpeakingPacking(@RequestParam String id){
        WebResult webResult = null;
        try {
            webResult = speakingPackageBiz.deleteSpeakingPackageById(id);
        }catch (Exception e){
            e.printStackTrace();
            webResult = WebResultUtils.getExceptionCharWebResult("");
        }finally {
            if(webResult==null)
                webResult = WebResultUtils.getFailCharWebResult("");
        }
        return webResult;
    }

    /**
     *
     * */
    @ResponseBody
    @RequestMapping("/getSpeakingPackageType")
    public Map<String,Object> getSpeakingPackageType(){
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> maps1 = new HashMap<String,Object>();
        maps1.put("id","111");
        maps1.put("name","111");
        maps1.put("open","false");
        maps1.put("children",null);
        maps1.put("checked",false);
        list.add(maps1);

        Map<String,Object> maps2 = new HashMap<String,Object>();
        maps2.put("id","111");
        maps2.put("name","111");
        maps2.put("open","false");
        maps2.put("children",list);

        Map<String,Object> maps = new HashMap<String,Object>();
        maps.put("0",maps1);
        maps.put("1",maps2);
        maps.put("2",maps1);

        return maps;
    }

    /**
     * @param id                 流程话术的id
     * @param recordFileUrl    录音文件
     * */
    @ResponseBody
    @RequestMapping("updateFlowStepRecordFileUrl")
    public WebResult updateFlowStepRecordFileUrl(String id,String recordFileUrl){
        WebResult webResult = new WebResult();
        try{
            SpeakingFlowStep speakingFlowStep = speakingFlowStepBiz.selectById(id);
            speakingFlowStep.setRecordFileUrl(recordFileUrl);
            speakingFlowStep.setHadUploadFile(true);
            speakingFlowStepBiz.update(speakingFlowStep);
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg(GlobalStatic.SUCCESS);
        }catch (Exception e){
            webResult.setMsg(GlobalStatic.EXCEPTION_CHAR);
            webResult.setCode(GlobalStatic.CODE_N);
        }
        return webResult;
    }
}
